import os

from pivelli.options import o as opts
from pivelli.options import cli_list
from pivelli import aptxml

# Choose according to requested action

if opts.action == 'disable':
	aptxml.delallcli()
elif opts.action == 'status':
	cli_dict = aptxml.askcli()
	print cli_dict
elif opts.action in ('enable', 'enable_all'):
	# Determine which CLIs must be registered
	cli_dict = aptxml.askcli()
	if opts.action == 'enable':
		requested_clis = cli_list
	# CLI sanity check (optional)
	#	for cli in requested_clis:
	#		assert cli in cli_dict, 'CLI %s is unknown to our gateway' % cli
	else:
		requested_clis = cli_dict.keys()
	
	# Register
	sip_data = aptxml.setcli(requested_clis)
		
	# Set routes, if asked to
	if hasattr(opts, 'route_command'):
		routed_proxies = []
		for cli, data in sip_data.items():
			if 'proxy' in data and data['proxy'] not in routed_proxies:
				params = data.copy()
				params['gateway'] = opts.gateway
				params['bind_ip'] = opts.bind_ip
				command = opts.route_command % params
				os.system(command)
				routed_proxies.append(data['proxy'])

	# Create Asterisk config files, if needed
	if opts.write_config:
		# Read templates
		try:
			peer_template = open(opts.peer_template, 'r').read()
		except AttributeError:
			peer_template = None
		try:
			reg_template = open(opts.reg_template, 'r').read()
		except AttributeError:
			reg_template = None
			
		for cli, data in sip_data.items():
			if data['error'] == '0':
				params = data.copy()
				params['cli'] = cli
				if peer_template:
					open(opts.peer_config_name % params, 'w').write(peer_template % params)
				if reg_template:
					open(opts.reg_config_name % params, 'w').write(reg_template % params)

	# Write out data
	if opts.verbose:
		print sip_data
		